package com.CMS.client.datasource;

import java.util.List;

import com.CMS.client.PrivilegeTypeService;
import com.CMS.client.PrivilegeTypeServiceAsync;
import com.CMS.server.domain.PrivilegeType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.DataSourceField;
import com.smartgwt.client.types.DSDataFormat;
import com.smartgwt.client.types.DSOperationType;
import com.smartgwt.client.types.DSProtocol;
import com.smartgwt.client.types.FieldType;
import com.smartgwt.client.widgets.grid.ListGridRecord;

public class TypeLookupDataSource extends DataSource{

	public TypeLookupDataSource(){
		setDataProtocol(DSProtocol.CLIENTCUSTOM);
        setDataFormat(DSDataFormat.CUSTOM);
        setClientOnly(false);
        addField(new DataSourceField("key", FieldType.INTEGER, "Key", 50, true));
        addField(new DataSourceField("value", FieldType.TEXT, "Value", 50, true));
	}
	
	@Override
    protected Object transformRequest(DSRequest request) {
        String requestId = request.getRequestId();
        final DSResponse response = new DSResponse();
        response.setAttribute("clientContext", request.getAttributeAsObject("clientContext"));
        response.setStatus(0);
        if (request.getOperationType() == DSOperationType.FETCH) {
        	PrivilegeTypeServiceAsync rpc = GWT.create(PrivilegeTypeService.class);
        	try {
				rpc.fetch(new AsyncCallback<List<PrivilegeType>>() {
					
					@Override
					public void onSuccess(List<PrivilegeType> result) {
						response.setTotalRows(result.size());
						ListGridRecord[] records = new ListGridRecord[result.size()];
						for(int i=0; i<result.size(); i++){
							ListGridRecord record = new ListGridRecord();
							record.setAttribute("key", result.get(i).getId());
							record.setAttribute("value", result.get(i).getDescription());
							records[i] = record;
						}
						response.setData(records);
					}
					
					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
        processResponse(requestId, response);
        return request.getData();
    }
}
